package cn.jsj.machine.controller;

import cn.jsj.machine.exceptions.MyRuntimeIdentityException;
import cn.jsj.machine.service.UserService;
import cn.jsj.machine.tool.HashMapBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import java.util.Map;

@Validated
@CrossOrigin
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private HashMapBuilder hashMapBuilder;

    @Valid
    @ResponseBody
    @RequestMapping(value = "login",method = {RequestMethod.POST},params = {"account","password"})
    public Map<String, Object> userLogin(@RequestParam("account") Integer userAccount,@RequestParam("password") String password){
        Map<String,Object> result = null;
        try {
            Integer i = this.userService.userLogin(userAccount, password);
            if(i == -1){
                result = this.hashMapBuilder.build(0,"请检查您的用户名和密码",null);
            }else{
                result = this.hashMapBuilder.build(1,"登陆成功",i);
            }
        }catch (ConstraintViolationException | MyRuntimeIdentityException e){
             result = this.hashMapBuilder.build(0,"请检查您输入的信息是否符合要求",null);
        }catch (Exception e){
            throw e;
        }
        return result;
    }
}
